/*
 * @Descripttion: 
 * @version: 
 * @Author: TT
 * @Date: 2023-03-19 20:59:21
 * @LastEditors: TT
 * @LastEditTime: 2023-03-27 16:33:02
 */

import 'package:hzy_normal_tool/hzy_normal_tool.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionHelper {
  static Function defaultCall = () {};

  ///检查权限
  static void check(
    List<Permission> permissionList, {
    String? errMsg,
    Function? onSuccess,
    Function(Permission? permission)? onFailed,
    Function? onOpenSetting,
  }) async {
    bool flag = true;
    Permission? permission;
    for (var value in permissionList) {
      var status = await value.status;
      if (!status.isGranted) {
        flag = false;
        permission = value;
        break;
      }
    }
    dprint(permission.toString());
    if (!flag) {
      PermissionStatus permissionStatus =
          await requestPermission(permissionList);
      dprint(permissionStatus);
      if (permissionStatus.isGranted) {
        //权限通过
        onSuccess != null ? onSuccess() : defaultCall();
      } else if (permissionStatus.isDenied) {
        //权限拒绝， 需要区分IOS和Android，二者不一样
        onFailed != null ? onFailed(permission) : defaultCall();
      } else if (permissionStatus.isPermanentlyDenied) {
        //权限永久拒绝，且不在提示，需要进入设置界面，IOS和Android不同
        onOpenSetting != null ? onOpenSetting() : defaultCall();
      } else if (permissionStatus.isRestricted) {
        //活动限制（例如，设置了家长///控件，仅在iOS以上受支持。
        //IOS单独处理
        onOpenSetting != null ? onOpenSetting() : defaultCall();
      } else if (permissionStatus.isLimited) {
        //IOS单独处理
        onOpenSetting != null ? onOpenSetting() : defaultCall();
      }
    } else {
      //权限通过
      onSuccess != null ? onSuccess() : defaultCall();
    }
  }

  //申请权限
  static Future<PermissionStatus> requestPermission(
      List<Permission> permissionList) async {
    Map<Permission, PermissionStatus> statuses = await permissionList.request();
    PermissionStatus currentPermissionStatus = PermissionStatus.granted;
    statuses.forEach((key, value) {
      if (!value.isGranted) {
        currentPermissionStatus = value;
        return;
      }
    });
    return currentPermissionStatus;
  }

  static configPermissionMsg({required Permission permission}) {
    String msg = "";
    if (permission == Permission.bluetooth) {
      msg = "请打开手机蓝牙功能";
    } else if (permission == Permission.bluetoothAdvertise) {
      /// Android：允许用户使此设备可被其他用户发现
      msg = "请允许用户使此设备可被其他用户发现";
    } else if (permission == Permission.bluetoothConnect) {
      /// Android：允许用户连接已配对的蓝牙设备。
      msg = "请允许用户连接已配对的蓝牙设备";
    } else if (permission == Permission.bluetoothScan) {
      /// Android：允许用户查找蓝牙设备
      msg = "请允许用户查找蓝牙设备";
    } else if (permission == Permission.locationWhenInUse) {
      ///
      msg = "请允许用户使用位置信息";
    }
    return msg;
  }
}
